<?php
class GraduaMenu {

    protected $items;

    /**
     * @return GraduaMenu
     */
    static function build() {
        return new GraduaMenu;
    }

    /**
     * @return GraduaMenu
     */
    function addItem($href, $onClick, $title, $arCredentials) {
        if($arCredentials && !is_array($arCredentials)) {
            $arCredentials = array($arCredentials);
        }
        $this->items[] = new GraduaMenuItem($href, $onClick, $title, $arCredentials);
        return $this;
    }

    function toArray($arUserCredentials) {
        $ar = array();
        foreach($this->items as $item) {
            //echo '1';
            //Dbg::x($arUserCredentials);
            if($item->hasOneOfTheCredentials($arUserCredentials)) {
                //echo '2';
                $ar[] = $item->toArray();
            }
        }
        return array('items'=>$ar);
    }
}

class GraduaMenuItem {

    protected $href;
    protected $onClick;
    protected $title;
    protected $arCredentials;
    
    function __construct($href, $onClick, $title, $arCredentials) {
        $this->href = $href;
        $this->onClick = $onClick;
        $this->title = $title;
        $this->arCredentials = $arCredentials;
    }

    function hasOneOfTheCredentials($arCredentials) {
        if(count($this->arCredentials) === 0) return true;
        foreach($this->arCredentials as $credential) {
            foreach($arCredentials as $cred) {
                if($cred == $credential) return true;
            }
        }
        return false;
    }

    function toArray() {
        return array(
            'href'=>$this->href ? $this->href : 'javascript:;',
            'onClick'=>$this->onClick,
            'title' => $this->title
        );
    }
}
?>
